<%@page
	import="org.springframework.security.core.context.SecurityContextHolder"%>
<%@page import="org.apache.commons.lang.StringUtils"%>
<%@page import="org.apache.commons.lang.time.DateFormatUtils"%>
<%@page import="org.springframework.util.CollectionUtils"%>
<%@page import="java.util.Collection"%>
<%@ include file="../common/common_include.jsp"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%
	UserInfo user = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
	String username = user.getName();
	String siteName = user.getSiteName();
	DutyForm form = (DutyForm) request.getAttribute("command");
	String siteId = form.getSiteId()!=null?form.getSiteId():"";
	String deptId = form.getDeptId()!=null?form.getDeptId():"";
	String dutyTime = form.getDutyDate()!=null?form.getDutyDate():"";
	String defaultSiteId = request.getAttribute("defaultSiteid") + "";
%>

<div>
	<div class="breadcrumb">
		<div class="bcIcon"></div>
		<ul class="bcNav">
			<li>复制值班信息</li>
		</ul>
	</div>
	<div class="oaTable">
		<table class="formTable">
			<tr>
				<td>
					<div class="box FormTools">
						所属公司： <select id="siteList" class="easyui-combobox" name="siteid"
							style="width: 100px;"></select> 
						部门： <select id="deptList"
							class="easyui-combobox" name="deptId" style="width: 100px;"></select>
						时间： <input id="dutyTime" name="dutyTime" type="text"
							class="easyui-datebox"> <input type="button"
							class="searchSubmit" onclick="javascript:initGrid()" value="搜索" />
							<span style="color:lightblue;">------点击后请稍等--</span>
						复制为： <input id="forDutyTime" name="forDutyTime" type="text"
							class="easyui-datebox">周
					</div>
				</td>
			</tr>
			<tr>
				<td>提示：<span>如果此页下面表单不显示请把IE浏览升级到IE8以上，或用火狐与谷歌浏览器</span></td>
			</tr>
		</table>
	</div>
	<form target="_coreIframe">
		<table id="dg" class="easyui-datagrid" title="复制值班信息---单击可编辑"
			style="width: 900px; height: 600px">
		</table>
	</form>
	<iframe id="_coreIframe" name="_coreIframe" style="display: none;"></iframe>
</div>
<script>
	var siteid ;
	var deptid ;
	$('#dg').datagrid({
	rownumbers:true,
	singleSelect:true,
	iconCls: 'icon-edit',
	collapsible:true,
	pagination:false,
	url:global.contextPath + '/duty/copySearch',
	columns: [[  
	             {title: '公司', field: 'siteId', width: 105,align:'center',
	            	formatter:function(value,row){
							return '<%=siteName%>';
						},
	            	 editor:{
	            	 type:'combobox',
	            	 options:{
	            		valueField:'siteId',
						textField:'siteName',								
						method:'get',
						url:global.contextPath + '/duty/datagridSites',
	                    panelHeight: 'auto',
	                    editable:false,
	                    disabled:true,
						required: true
						}							
					}		             
	             },  
	             { title: '部门', field: 'deptId', width: 70,align:'center',
	            	 formatter:function(value,row){
							return row.deptName;
						},
	            	 editor:{
	            	 type:'combobox',
	            	 options:{
							url:global.contextPath + '/duty/datagridDepts?siteId=' + '<%=siteId%>',
							valueField:'deptId',
							textField:'deptName',								
							method:'get',
							onSelect:function(data){
		                    	var row = $('#dg').datagrid('getSelected');  
                                var rowIndex = $('#dg').datagrid('getRowIndex',row);//获取行号  
                                var deptId = data.deptId;
                                var target = $('#dg').datagrid('getEditor', {'index':rowIndex,'field':'userId'}).target;  
                                var scheduletarget = $('#dg').datagrid('getEditor', {'index':rowIndex,'field':'scheduleId'}).target;  
                                var url = global.contextPath + '/duty/datagridUsers?siteId=' + '<%=siteId%>'+'&deptId='+deptId;
                                var shceduleurl = global.contextPath + '/duty/datagridSchedules?siteId=' + '<%=siteId%>' + '&deptId='+deptId;
                                target.combobox('reload', url);//联动下拉列表重载 
                                scheduletarget.combobox('reload', shceduleurl);//联动下拉列表重载  
		                    },
		                    onChange:function(){
		                    	var row = $('#dg').datagrid('getSelected');  
                                var rowIndex = $('#dg').datagrid('getRowIndex',row);//获取行号  
                                var target1 = $('#dg').datagrid('getEditor', {'index':rowIndex,'field':'userId'}).target; 
                                var scheduletarget = $('#dg').datagrid('getEditor', {'index':rowIndex,'field':'scheduleId'}).target;
                                target1.combobox('clear');
                                scheduletarget.combobox('clear');
		                    }, 
		                    panelHeight: '300',
		                    editable:false,
							required: true
						}
					} 
	             },  
	             { title: '员工', field: 'userId', width: 120,align:'center',
	            	 formatter:function(value,row){
							return row.userName;
						},
	            	 editor:{
	            	 type:'combobox',
	            	 options:{
						 url:global.contextPath + '/duty/datagridUsers?siteId=' + '<%=siteId%>'+'&deptId='+'<%=deptId%>',
	            		 method:'get',
	            		 valueField:'userId',
						 textField:'userName',
						 editable:true,
						 panelHeight: '300',
						 onSelect:function(data){
							 var row = $('#dg').datagrid('getSelected');  
                             var rowIndex = $('#dg').datagrid('getRowIndex',row);//获取行号  
                             var userId = data.userId;
                             var telNotarget = $('#dg').datagrid('getEditor', {'index':rowIndex,'field':'userTelNo'}).target;
                             var url = global.contextPath + '/duty/datagridTelNo?userId=' + userId;
                             telNotarget.combobox('reload', url);//联动下拉列表重载 
						},
						onChange:function(){
							var row = $('#dg').datagrid('getSelected');  
                            var rowIndex = $('#dg').datagrid('getRowIndex',row);//获取行号  
                            var telNotarget = $('#dg').datagrid('getEditor', {'index':rowIndex,'field':'userTelNo'}).target;
                            telNotarget.combobox('clear');
	                    }, 
	                     panelHeight: '300' ,
						 required: true
					 }
	            	 
					} 
	             },  
				 { title: '值班日期', field: 'dutyDateStr', width: 150, align:'center' ,
					 editor:{
						type: 'datebox',
						options:{			            		 
		                     editable:false,
							 required: true
		            	 }
					 }
				 },
				 { title: '值班班次', field: 'scheduleId', width: 120,align:'center',
	            	 formatter:function(value,row){
	            		 return row.scheduleName;
						},
	            	 editor:{
	            		 type:'combobox',
		            	 options:{
		            		 url:global.contextPath + '/duty/datagridSchedules?siteId=' + '<%=siteId %>' + '&deptId='+'<%=deptId %>',
		            		 valueField:'scheduleId',
		            		 textField:'scheduleName',
							 panelHeight: 'auto',
							 editable:false,
							 required: true
		            	 } 
	            	 }
						
				 } ,
				 { title: '电话', field: 'userTelNo', width: 120,align:'center',
	            	 formatter:function(value,row){
	            		 return row.userTelNo;
						},
	            	 editor:{
	            		 type:'combobox',
		            	 options:{
	            			valueField:'userId',
	            			textField:'telNo',
	            			editable:true,
	            			required:true
		            	 } 
	            	 }
				 } ,
	        ]],
	toolbar:[{  
        id: 'btnAdd',  
        text: '<font size="3px">添加</font>',  
        iconCls: 'icon-add',
        handler: function () {  
        	append();//实现添加记录的页面  
        }
    }, '-', {  
        id: 'btnDelete',  
        text: '<font size="3px">删除</font>',  
        iconCls: 'icon-remove',  
        handler: function () {  
        	removeit();//实现直接删除数据的方法  
        }  
    }, '-', {  
        id: 'btnAccept',  
        text: '<font size="3px">提交</font>',  
        iconCls: 'icon-save',  
        handler: function () {  
        	accept();//实现直接提交数据的方法  
        }  
    }, '-', {  
        id: 'btnReject',  
        text: '<font size="3px">取消</font>',  
        iconCls: 'icon-undo',  
        handler: function () {  
        	reject();//取消  
        }  
    }],
    onClickCell: onClickCell,
	onEndEdit: onEndEdit
});
var editIndex = undefined;
var backDutyDate = undefined;
function endEditing(){
	if (editIndex == undefined){return true}
	if ($('#dg').datagrid('validateRow', editIndex)){
		$('#dg').datagrid('endEdit', editIndex);
		editIndex = undefined;
		return true;
	} else {
		return false;
	}
}
function onClickCell(index, field){
	if (editIndex != index){			
		if (endEditing()){
			$('#dg').datagrid('selectRow', index)
					.datagrid('beginEdit', index);
			var ed = $('#dg').datagrid('getEditor', {index:index,field:field});
			if (ed){
				($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).focus();
			}
			editIndex = index;
		} else {
			setTimeout(function(){
				$('#dg').datagrid('selectRow', editIndex);
			},0);
		}
	}
}
function onEndEdit(index, row){
	var siteed = $(this).datagrid('getEditor', {
		index: index,
		field: 'siteId'
	});
	var depted = $(this).datagrid('getEditor', {
		index: index,
		field: 'deptId'
	});
	var usersed = $(this).datagrid('getEditor', {
		index: index,
		field: 'userId'
	});
	var scheduleed = $(this).datagrid('getEditor', {
		index: index,
		field: 'scheduleId'
	});
	var usertelnoed = $(this).datagrid('getEditor', {
		index: index,
		field: 'userTelNo'
	});
	var dutydateed = $(this).datagrid('getEditor', {
		index: index,
		field: 'dutyDateStr'
	});
	row.deptName = $(depted.target).combobox('getText');
	row.userName = $(usersed.target).combobox('getText');
	row.scheduleName = $(scheduleed.target).combobox('getText');
	row.userTelNo = $(usertelnoed.target).combobox('getText');
	backDutyDate = $(dutydateed.target).combobox('getValue');
}
function append(){
	if (endEditing()){
		$('#dg').datagrid('appendRow',{reason:''});
		editIndex = $('#dg').datagrid('getRows').length-1;
		$('#dg').datagrid('selectRow', editIndex)
				.datagrid('beginEdit', editIndex);
        var siteTarget = $('#dg').datagrid('getEditor', {'index':editIndex,'field':'siteId'}).target;
        var deptTarget = $('#dg').datagrid('getEditor', {'index':editIndex,'field':'deptId'}).target;
        siteTarget.combobox('setValue', '<%=siteId%>');
        siteTarget.combobox('setText', '<%=user.getSiteName()%>');
        deptTarget.combobox('setValue', '<%=deptId%>');
	}
}
function removeit(){
	if (editIndex == undefined){return}
	$('#dg').datagrid('cancelEdit', editIndex)
			.datagrid('deleteRow', editIndex);
	editIndex = undefined;
}
function accept(){
	if (endEditing()){
		var rows = $('#dg').datagrid("getRows");
		if(rows.length >0){
			var lastDate = new Date(backDutyDate.replace(/-/g, "/"));
			var isSunday3 = lastDate.getDay();
			if(isSunday3==0){
				isSunday3 = 7;
			}
			var newDate = new Date(lastDate.setDate(lastDate.getDate() + 1 - isSunday3));
			backDutyDate = formatDate(newDate);//周一
			var dutyJson = JSON.stringify($('#dg').datagrid("getRows"));
			XF.Duty.submitCopyDuty(dutyJson,'<%=siteId%>','<%=deptId%>',backDutyDate);
		}else{
			alert("表格无添加记录")
		}			
	}else{
		alert("红色必填项，时段必填其一。")
	}
	
}
function reject(){
	XF.Duty.manageDuty();
}
function getChanges(){
	var rows = $('#dg').datagrid('getChanges');
	alert(rows.length+' rows are changed!');
}
	//重新加载数据
	function initGrid(){
		var dutyDate = $("#dutyTime").datebox('getValue');
		var siteId = $("#siteList").combobox('getValue');
		var deptId = $("#deptList").combobox('getValue');
		var params = {'siteId':siteId,'deptId':deptId,'dutyDate':dutyDate};
		$('#dg').datagrid('load',params);
	}
	
	//选择器相关
	$('#siteList').combobox({
		/* url:global.contextPath + '/company/siteList', */
		valueField:'siteid',
		textField:'sitename',
		editable:false,
		disabled:true
	});
	$('#deptList').combobox({
		url:global.contextPath + '/duty/datagridDepts?siteId=' + '<%=siteId%>',
		valueField:'deptId',
		textField:'deptName',
		editable:false,
		disabled:true
	});
	$('#siteList').combobox('setValue', '<%=siteId%>');
	$('#siteList').combobox('setText', '<%=siteName%>');
	$('#deptList').combobox('setValue', '<%=deptId%>');
	$("#dutyTime").datebox({
		formatter:XF.dateFormatter,
		parser:XF.dateParse,
		editable:false,
	});
	$("#forDutyTime").datebox({
		formatter:XF.dateFormatter,
		parser:XF.dateParse,
		editable:false
	});
	
	<%if (StringUtils.isNotBlank(dutyTime)) {%>
		$("#dutyTime").datebox("setValue","<%=dutyTime%>".replace(/-/g,'/'));
	<%}%>
	//设置值班日期为目的值班日期
	$(function() {
		$('#forDutyTime').datebox(
				{
					onSelect : function(date) {
						var isSunday = date.getDay();
						if(isSunday==0){
							isSunday = 7;
						}
						copyDay = date.setDate(date.getDate() + 1 - isSunday);//周一
						var rows = $("#dg").datagrid("getRows");
						if (rows.length > 0) {
							for (var i = 0; i < rows.length; i++) {
								if (endEditing()){
									$('#dg').datagrid('selectRow', i)
										.datagrid('beginEdit', i);
									editIndex = i;
									var sitetar= $('#dg').datagrid('getEditor', {'index':i,'field':'siteId'}).target;  
									var depttar= $('#dg').datagrid('getEditor', {'index':i,'field':'deptId'}).target;
									var usertar= $('#dg').datagrid('getEditor', {'index':i,'field':'userId'}).target;
									var scheduletar= $('#dg').datagrid('getEditor', {'index':i,'field':'scheduleId'}).target;
									sitetar.combobox('setText',rows[i]['siteName']);
									depttar.combobox('setText',rows[i]['deptName']);
									usertar.combobox('setText',rows[i]['userName']);
									scheduletar.combobox('setText',rows[i]['scheduleName']);
									var dutyDateTarget = $('#dg').datagrid(
											'getEditor', {
												'index' : i,
												'field' : 'dutyDateStr'
											}).target;
									var oldDate = new Date(dutyDateTarget.datebox('getValue').replace(/-/g, "/"));
									var isSunday2 = oldDate.getDay();
									if(isSunday2==0){
										isSunday2 = 7;
									}
									var dutyDate = oldDate.setDate(oldDate.getDate() + 1 - isSunday2);//周一
									var days = (copyDay - dutyDate)/ (24 * 3600 * 1000);
									var basicDate = new Date(dutyDateTarget.datebox('getValue').replace(/-/g, "/"));
									var forDate = new Date(basicDate.setDate(basicDate.getDate()+days));
									var changeDate = formatDate(forDate);
									dutyDateTarget.datebox('setValue',changeDate);
								}
								$('#dg').datagrid('endEdit', i);
							}
						}
					}
		});
	});
	
	function formatDate(date) {  
	    var y = date.getFullYear();  
	    var m = date.getMonth() + 1;  
	    m = m < 10 ? '0' + m : m;  
	    var d = date.getDate();  
	    d = d < 10 ? ('0' + d) : d;  
	    return y + '-' + m + '-' + d;  
	};  
</script>
<style type="text/css">
.datagrid {
	margin: 20px
}
</style>
